const moment = require('moment')
const { Controller } = require('egg')

class BillController extends Controller {

    /**
     * 添加账单
     * @returns 
     */
    async add() {
        const { ctx, app } = this;
        // 获取请求中携带的参数
        const { amount, type_id, type_name, date, pay_type, remark = ''} = ctx.request.body;
        // 判断参数是否为空
        if (!amount || ! type_id || ! type_name || !date || !pay_type) {
            ctx.body = {
                code: 400,
                msg: '参数错误',
                date: null
            }
        }

        try {
            let user_id
            const token = ctx.request.header.authorization;

            const decode = await app.jwt.verify(token, app.config.jwt.secret);
            if(!decode) return
            user_id = decode.id

            const result = await ctx.service.bill.add({
                amount,
                type_id,
                type_name,
                date,
                pay_type,
                remark,
                user_id
            });

            ctx.body = {
                code: 200,
                msg: '请求成功',
                data: null
            }
        } catch (err) {
            ctx.body = {
                code: 500,
                msg: '系统错误',
                date: null
            }
        }
    }

    /**
     * 获取账单列表
     * @returns 
     */
    async list() {
        const { ctx, app } = this;
        const { date, page = 1, page_size = 5, type_id = 'all'} = ctx.query

        try {
            // 通过token解析，拿到user_id
            let user_id
            const token = ctx.request.header.authorization;
            const decode = await app.jwt.verify(token, app.config.jwt.secret);
            if (!decode) return
            user_id = decode.id
            // 拿到当前用户的账单列表
            const list = await ctx.service.bill.list(user_id)
            // 过滤出月份和类型对应的账单列表
            const _list = list.filter(item => {
                if (type_id != 'all') {
                    return moment(Number(item.date)).format('YYYY-MM') == date && type_id == item.type_id
                }
                return moment(Number(item.date)).format('YYYY-MM') == date
            })

            // 格式化数据
            let listMap = _list.reduce((curr, item) => {
                // 将第一个账单的时间格式化为YYYY-MM-DD
                const date = moment(Number(item.date)).format('YYYY-MM-DD')
                // 如果能在累加的数组中找到当前日期的date，在数组中的加入当前项到bills数组
                if (curr && curr.length && curr.findIndex(item => item.date == date) > -1) {
                    const index = curr.findIndex(item => item.date == date)
                    curr[index].bills.push(item)
                }
                // 找不到，则新建一项
                if (curr && curr.length && curr.findIndex(item => item.date == date) == -1) {
                    curr.push({
                        date,
                        bills: [item]
                    })
                }
                // 如果curr为空数组，默认添加第一个张单项，格式化
                if (!curr.length) {
                    curr.push({
                        date,
                        bills: [item]
                    })
                }
                return curr
                    // 按时间倒序排序
            },[]).sort((a,b) => moment(b.date) - moment(a.date))

            // 分页处理
            const filterListMap = listMap.slice((page - 1) * page_size, page * page_size)

            // 计算当月总收入和支出
            // 获取当月所有账单列表
            let __list = list.filter( item => moment(Number(item.date)).format('YYYY-MM') == date)
            // 累加计算支出
            let totalExpense = __list.reduce((curr, item) => {
                if (item.pay_type == 1) {
                    curr += Number(item.amount)
                    return curr
                }
                return curr
            },0)
            // 计算收入
            let totalIncome = __list.reduce((curr,item) => {
                if (item.pay_type == 2) {
                    curr += Number(item.amount)
                    return curr
                }
                return curr
            },0)
            // 返回数组
            ctx.body = {
                code: 200,
                msg: '请求成功',
                data: {
                    totalExpense,
                    totalIncome,
                    totalPage: Math.ceil(listMap.length / page_size),
                    list: filterListMap || []
                }
            }
        } catch(error) {
            console.log(error)
            ctx.body = {
                code: 500,
                msg: '系统错误',
                date: null
            }
        }
    } 

    /**
     * 获取账单详情
     */
    async detail() {
        const { ctx,app } = this;
        const { id = '' } = ctx.query;

        let user_id
        const token = ctx.request.header.authorization;
        // 获取当前用户信息
        const decode = await app.jwt.verify(token, app.config.jwt.secret);
        if (!decode) return
        user_id = decode.id

        if (!id) {
            ctx.body = {
                code: 500,
                msg: '订单id不能为空',
                data: null
            }
            return
        }

        try {
            // 获取账单详情
            const detail = await ctx.service.bill.detail(id, user_id);
            ctx.body = {
                code: 200,
                msg: '请求成功',
                detail: detail
            }
        } catch(error) {
            ctx.body = {
                code: 500,
                msg: '系统错误',
                data: null
            }
        }
    }

    async update() {
        const { ctx, app } = this;
        const { id, amount, type_id, type_name, date, pay_type, remark = '' } = ctx.request.body;

        if (!amount || !type_id || !type_name || !date || !pay_type) {
            ctx.body = {
                code: 400,
                msg: '参数错误',
                data: null
            }
        }

        try {
            let user_id
            const token = ctx.request.header.authorization;
            const decode = await app.jwt.verify(token, app.config.jwt.secret);
            if (!decode)  return
            user_id = decode.id

            const result = await ctx.service.bill.update({
                id,
                amount,
                type_id,
                type_name,
                date,
                pay_type,
                remark,
                user_id
            });
            ctx.body = {
                code: 200,
                msg: '请求成功',
                data: null
            }
        } catch(error) {
            ctx.body = {
                code: 500,
                msg: '系统错误',
                date: null
            }
        }
    }

    async delete() {
        const { ctx, app } = this;
        const { id } = ctx.request.body;
        
        if (!id) {
            ctx.body = {
                code:400,
                msg:'参数错误',
                data: null
            }
        }

        try {
            let user_id
            const token = ctx.request.header.authorization;
            const decode = await app.jwt.verify(token, app.config.jwt.secret);
            if (!decode) return 
            user_id = decode.id
            const result = await ctx.service.bill.delete(id,user_id);

            ctx.body = {
                code: 200,
                msg: '请求成功',
                data: null
            }
        } catch(error) {
            ctx.body = {
                code: 500,
                msg: '系统错误',
                data: null
            }
        }
    }

    async data() {
        const { ctx, app } = this;
        const { date = '' } = ctx.query;

        let user_id
        const token = ctx.request.header.authorization;
        const decode = await app.jwt.verify(token, app.config.jwt.secret);
        if (!decode) return 
        user_id = decode.id

        try {
            const result = await ctx.service.bill.list(user_id);
            const start = moment(date).startOf('month').unix() * 1000;
            const end = moment(date).endOf('month').unix() * 1000;
            const _data = result.filter(item => (Number(item.date) > start && Number(item.date) < end))

            // 总支出
            const totalExpense = _data.reduce((arr, cur) => {
                if (cur.pay_type == 1) {
                    arr += Number(cur.amount);
                }
                return arr;
            },0)
            // 总收入
            const totalIncome = _data.reduce((arr, cur) => {
                if(cur.pay_type == 2) {
                    arr += Number(cur.amount);
                }
                return arr
            },0)
            // 收支构成
            let totalData = _data.reduce((arr,cur) => {
                const index = arr.findIndex(item => item.type_id == cur.type_id)
                if (index == -1) {
                    arr.push({
                        type_id: cur.type_id,
                        type_name: cur.type_name,
                        pay_type: cur.pay_type,
                        number: Number(cur.amount)
                    })
                }
                if (index > -1) {
                    arr[index].number += Number(cur.amount);
                }

                return arr;
            },[])

            totalData = totalData.map(item => {
                item.number = Number(Number(item.number).toFixed(2));
                return item;
            })

            ctx.body = {
                code: 200,
                msg: '请求成功',
                data: {
                    totalExpense: Number(totalExpense).toFixed(2),
                    totalIncome: Number(totalIncome).toFixed(2),
                    totalData: totalData || []
                }
            }
        } catch(error) {
            console.log(error)
        }
    }
}

module.exports = BillController